package com.example.week3work.controller;


import com.alibaba.fastjson.JSON;
import com.example.week3work.config.AjaxResult;
import com.example.week3work.entity.Movies;
import com.example.week3work.service.IMoviesService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bw
 * @since 2022-02-09
 */@Slf4j
@RestController
@RequestMapping("/movies")
public class MoviesController {

    @Autowired
    IMoviesService iMoviesService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    KafkaTemplate kafkaTemplate;
    @RequestMapping("list")
    public AjaxResult list(Movies movies, @RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "3") Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Movies> list=iMoviesService.select(movies);
        PageInfo<Movies> pageInfo = new PageInfo<>(list);
        return  AjaxResult.ok(pageInfo);
    }

    @RequestMapping("add")
    public  AjaxResult add(Movies movies){
        String token = UUID.randomUUID().toString();
        if(StringUtils.isBlank(token)||!redisTemplate.opsForValue().setIfAbsent(token,null,24, TimeUnit.HOURS)){
            log.info("表单重复提交了");
            return AjaxResult.err(400,"表单重复提交了");
        }
        kafkaTemplate.send("movies", JSON.toJSONString(movies));
        boolean save = iMoviesService.save(movies);
        return AjaxResult.ok(save);
    }
}
